package cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @projectName: JUC
 * @package: cas
 * @className: casDemo
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/4 17:32
 * @version: 1.0
 */
public class casDemo {
    //CAS compareAndSet 比较并交换
    public static void main(String[] args) {
        //AtomicInteger atomicStampedReference = new AtomicInteger(2020);
        // 注意 如果 泛型是一个包装类，注意对象的引用问题，
        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("a1 =>" + stamp);
            System.out.println("a2 =>" + atomicStampedReference.compareAndSet(1, 2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a2 =>" + atomicStampedReference.getStamp());
            System.out.println("a3 =>" + atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a3 =>" + atomicStampedReference.getStamp());
        }, "a").start();
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("b1 =>" + stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b2 =>" + atomicStampedReference.compareAndSet(1, 6, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("b2 =>" + atomicStampedReference.getStamp());
        }, "b").start();
    }
}
